package com.han.agent.tools;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.method.MethodToolCallbackProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.Map;

/**
 * @author han
 */
@Service
public class RegionService {

    @Tool(description = "获取所有运输区域")
    public String getRegion() throws JsonProcessingException {
        RestTemplate restTemplate = new RestTemplate();
        ObjectMapper objectMapper = new ObjectMapper();
        URI uri = URI.create("https://xxx.com");

        String str = "{\"pageNum\":1,\"pageSize\":100,\"data\":{\"organizationIds\":[]}}";
        Map map = objectMapper.readValue(str, Map.class);

        HttpEntity<?> httpEntity = new HttpEntity<>(map, buildGlobalHeaders());
        ResponseEntity<Object> exchange = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, Object.class);

        return objectMapper.writeValueAsString(exchange.getBody());
    }

    @Bean
    public ToolCallbackProvider regionTools(RegionService regionService) {
        return MethodToolCallbackProvider.builder().toolObjects(regionService).build();
    }

    private HttpHeaders buildGlobalHeaders() {
        HttpHeaders header = new HttpHeaders();
        header.add(HttpHeaders.AUTHORIZATION, "Bearer token");
        header.add("lang", "zh");
        header.add("User-Time-Zone", "Europe/Paris");
        return header;
    }

}
